﻿using Com.JunCaiSoft.AddressManage.Entity;
using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Extension;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.ConstructionCashFlow.Entity;
using Com.JunCaiSoft.Hr.Entity;
using Com.JunCaiSoft.Law.Dto;
using Com.JunCaiSoft.Law.Entity;
using Com.JunCaiSoft.Law.IDao;
using Com.JunCaiSoft.Law.Model;
using Com.JunCaiSoft.NoticeSystem.Entity;
using Com.JunCaiSoft.NoticeSystem.Model.Notice;
using Com.JunCaiSoft.WXWork.Common;
using Com.JunCaiSoft.WXWork.RestFul;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.Law.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    /// <summary>
    /// 案件信息
    /// </summary>
    public class CaseMainController : BaseController<CaseMainView, CaseMainItem, CaseMain, Guid>
    {
        /// <summary>
        /// 配置
        /// </summary>
        private IConfiguration Configuration { get; set; }
        /// <summary>
        /// 配置环境
        /// </summary>
        private readonly IWebHostEnvironment HostingEnvironment;
        /// <summary>
        /// APICoreBaseURL
        /// </summary>
        private readonly String APICoreBaseURL;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="CaseMainDao"></param>
        /// <param name="env"></param>
        public CaseMainController(ICaseMainDao CaseMainDao,IWebHostEnvironment env) : base(CaseMainDao)
        {
            var builder = new ConfigurationBuilder()
                               .SetBasePath(env.ContentRootPath)
                               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                               .AddJsonFile("DataBaseExcute.json", optional: true, reloadOnChange: true);
            HostingEnvironment = env;
            Configuration = builder.Build();
            APICoreBaseURL = Configuration.GetSection("APICores:BaseURL").Value;
        }
        /// <summary>
        /// 按案件ID单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public override async Task<ActionResult> DeleteSingleAsync(Guid Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<CaseMain>(x => x.Id == Id);

                await DaoAsync.DeleteListAsync<Notice>(x => x.SendData == Id);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 按案件ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<CaseMain>(x => DeleteList.Contains(x.Id));

                await DaoAsync.DeleteListAsync<Notice>(x => DeleteList.Contains(x.SendData));

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize, String keyword)
        {
            try
            {
                var columns = @" c.Id,
	                             c.Num,
	                             c.NumCode,
	                             p.Name CaseProject,
	                             c.PreserveStatus,
                                 pm.Name BranchCompany,
	                             c.CaseStatus,
	                             u.RealName,
	                             c.CreateTime  ";

                var tables = @" CaseMain c
	                            LEFT JOIN Project p ON c.CaseProject = p.Id
                                LEFT JOIN Partment pm ON p.Partment = pm.Id
	                            LEFT JOIN [User] u ON c.RegistOperator = u.Id ";

                var where = @" 1 = 1 ";

                List<SqlParameter> bankParams = new List<SqlParameter>() { };

                if (keyword != "" && keyword != null)
                {

                    where += " AND p.Name like @ProjectName ";

                    SqlParameter QueryProjectName = new SqlParameter("@ProjectName", "%" + keyword + "%");

                    bankParams.Add(QueryProjectName);

                }

                var tmpResultList = await DaoAsync.QuerySQLByPageQuickAsync<CaseMainItemDto>(pageIndex, pageSize, " c.CreateTime desc ", columns, tables, where, bankParams.Select(x => ((ICloneable)x).Clone()).ToArray());

                var resultList = new QueryData<CaseMainItem>();

                var itemList = new List<CaseMainItem>();

                resultList.totalCount = tmpResultList.totalCount;

                tmpResultList.items.ToList().ForEach(item => itemList.Add(item.MapTo<CaseMainItem>()));

                resultList.items = itemList;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(resultList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        [HttpGet]
        public override async Task<ActionResult> GetAsync(Guid Id)
        {
            try
            {
                var getOne = await DaoAsync.GetAsync<CaseMain>(Id);
                var result = getOne.MapTo<CaseMainView>();
                result.CaseProject = (await DaoAsync.GetAsync<Project>(getOne.CaseProject)).MapTo<CaseProject>();

                if(result.CaseProject != null && result.CaseProject.Partment != Guid.Empty.ToString())
                {
                    var companyStr = await DaoAsync.GetAsync<Partment>(Guid.Parse(result.CaseProject.Partment));
                    result.CaseProject.Partment = companyStr.Name;
                    result.CaseProject.PartmentLeader = companyStr.Boss;
                }

                var provinceStr = await DaoAsync.GetAsync<Administrative>(result.CaseProject.Province);
                result.CaseProject.Province = provinceStr != null ? provinceStr.Name : null;
                var cityStr = await DaoAsync.GetAsync<Administrative>(result.CaseProject.City);
                result.CaseProject.City = provinceStr != null ? cityStr.Name : null;
                var zoneStr = await DaoAsync.GetAsync<Administrative>(result.CaseProject.Zone);
                result.CaseProject.Zone = provinceStr != null ? zoneStr.Name : null;

                List<NoticeView> notices = new List<NoticeView>();

                (await DaoAsync.ListAsync<Notice>(x => x.SendData == result.Id)).ForEach(item => notices.Add(item.MapTo<NoticeView>()));

                foreach(var item in notices)
                {
                    switch (item.Group)
                    {
                        case 0:
                            item.Targets = item.Content.touser.Split('|').ToList();
                            break;
                        case 1:
                            item.Targets = item.Content.toparty.Split('|').ToList();
                            break;
                        case 2:
                            item.Targets = item.Content.totag.Split('|').ToList();
                            break;
                        default:
                            break;
                    }
                }

                result.NoticeData = notices;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch(Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 创建案件信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(CaseMainView entity)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                var saveone = entity.MapTo<CaseMain>();
                var result = await DaoAsync.InsertAsync(saveone);

                if (entity.NoticeData != null)
                {
                    entity.NoticeData.ForEach(item => item.SendData = saveone.Id);

                    foreach (var item in entity.NoticeData)
                    {
                        item.Content.textcard.description = item.Title;

                        var sendData = JsonConvert.SerializeObject(new SendTextCardInfo()
                        {
                            body = item.Content,
                            partment = PartmentEnum.法务监察中心
                        });

                        var sendresult = HttpExtension.HttpPost(APICoreBaseURL + "/WXWork/SendMessage/SendTextCardMessage", sendData, true, Request.Headers["Authorization"].ToString());

                        item.NoticeLog = sendresult;

                        await DaoAsync.InsertAsync<Notice>(item.MapTo<Notice>());
                    }
                }

                await DaoAsync.dbContext.Database.CommitTransactionAsync();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                await DaoAsync.dbContext.Database.RollbackTransactionAsync();
                throw e;
            }

        }
        /// <summary>
        /// 更新案件信息
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<CaseMainView> entityModel)
        {
            await DaoAsync.dbContext.Database.BeginTransactionAsync();

            var saveone = entityModel.entity.MapTo<CaseMain>();
            var result = await DaoAsync.UpdateAsync(saveone, entityModel.Id);

            if(entityModel.entity.NoticeData != null && entityModel.entity.NoticeData.Count != 0)
            {
                entityModel.entity.NoticeData.ForEach(item => item.SendData = saveone.Id);

                await DaoAsync.DeleteListAsync<Notice>(x => (!entityModel.entity.NoticeData.Select(y => y.Id).ToList().Contains(x.Id)) && x.SendData == saveone.Id);

                foreach (var item in entityModel.entity.NoticeData)
                {
                    if (item.ReSendNotice)
                    {
                        item.Content.textcard.description = item.Title;

                        var sendData = JsonConvert.SerializeObject(new SendTextCardInfo()
                        {
                            body = item.Content,
                            partment = PartmentEnum.法务监察中心
                        });

                        var sendresult = HttpExtension.HttpPost(APICoreBaseURL + "/WXWork/SendMessage/SendTextCardMessage", sendData, true, Request.Headers["Authorization"].ToString());

                        item.NoticeLog = sendresult;

                    }

                    if (item.Id == Guid.Empty)
                    {
                        await DaoAsync.InsertAsync<Notice>(item.MapTo<Notice>());
                    }
                    else
                    {
                        await DaoAsync.UpdateAsync<Notice>(item.MapTo<Notice>(), item.Id);
                    }
                }
            }
            else
            {
                await DaoAsync.DeleteListAsync<Notice>(x => x.SendData == saveone.Id);
            }

            await DaoAsync.dbContext.Database.CommitTransactionAsync();
            return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="currentuser"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> SendMessageQueue(Guid currentuser)
        {
            return await Task.Run(() => Content(JsonConvert.SerializeObject("")));
        }
    }
}
